# -*- coding: utf-8 -*-
from array import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtCore import Qt
from PyKDE4.kio import *
from PyKDE4.kdeui import *
from PyKDE4.kdecore import *
from PyKDE4.plasma import Plasma
from PyKDE4 import plasmascript
from PyKDE4.solid import Solid
from LoadCPU import LoadCPU
from MemoryUse import MemoryUse

class BWCBalancePlasmoid(plasmascript.Applet):
    def __init__(self, parent, args=None):
        plasmascript.Applet.__init__(self, parent)

  
    def init(self):
        """Инициализация настроек"""
        # Плазмоид имеет пользовательские настройки
        self.setHasConfigurationInterface(True)
        self.setAspectRatioMode(Plasma.IgnoreAspectRatio)
	
	self.begX = 20                   # Отступ от границы плазмоида по горозонтали
	self.begY = 20                   # Отступ от границы плазмоида по вертикали
	self.labelW = 200		 # Длина нарисованного label
	self.labelH = 20		 # Высота нарисованного label
	self.balanW = 20		 # Длина таблицы, показывающей моментальный ур. загр.
	self.histoW = 100		 # Длина таблицы, показывающей историю ур. загр.
	self.hbH = 40			 # Высота двух последних таблиц
	
	self.appletW = self.labelW + 30  #Длина плазмоида
	self.appletH = 300		 #Высота плазмоида
	
	# Флаги состояния настроек
	self.seebig = 1
	self.seecpu = 1
	self.seecpu0 = 1
	self.seecpu1 = 1
	self.seemem = 1
	self.seeswap = 1
      
	# Первоначальная инициализация показателей
	self.memuse = "00.00 %"		
	self.swapuse = "00.00 %"
	self.cpuload = "00.00 %"
        self.cpu0load = "00.00 %"
	self.cpu1load = "00.00 %" 
  
	self.theme = Plasma.Svg(self)
        self.theme.setImagePath("widgets/background")
        self.setBackgroundHints(Plasma.Applet.DefaultBackground)
	
	# Переменные классов обновления информации о состоянии системы
	self.load = LoadCPU("cpu") 
	self.load0 = LoadCPU("cpu0")
	self.load1 = LoadCPU("cpu1")
	self.mem = MemoryUse()
	
	# Инициализация нулями массивов статистики загрузки
	self.arrLen = self.histoW
	arr = range(self.arrLen)
	i = 0
	while i < self.arrLen:
	      arr[i] = 0
	      i +=1
	self.arrcpu = array('i', arr)
	self.arrcpu0 = array('i', arr)
	self.arrcpu1 = array('i', arr)
	self.arrmem = array('i', arr)    
	self.arrswap = array('i', arr)
	
	# И изменяем размеры плазмоида
        self.resize(self.appletW, self.appletH )
	self.updatelabels()
	
	#self.update()
	self.startTimer(1000)

   # def createConfigurationInterface(self, parent):
     #   self.widget = QWidget(parent)

    def updatelabels(self):
	self.cpuload = self.load.ReturnLoad()
	self.cpu0load = self.load0.ReturnLoad() 
	self.cpu1load = self.load1.ReturnLoad()
	self.memuse = self.mem.returnMemUse()
	self.swapuse = self.mem.returnSwapUse()
	
	self.arrcpu.append(int(float(self.cpuload[0:3])))
	self.arrcpu = self.arrcpu[1:self.arrLen+ 1]
	self.arrcpu0.append(int(float(self.cpu0load[0:3])))
	self.arrcpu0 = self.arrcpu0[1:self.arrLen+ 1]
	self.arrcpu1.append(int(float(self.cpu1load[0:3])))
	self.arrcpu1 = self.arrcpu1[1:self.arrLen+ 1]
	self.arrmem.append(int(float(self.memuse[0:3])))
	self.arrmem = self.arrmem[1:self.arrLen+ 1]
	self.arrswap.append(int(float(self.swapuse[0:3])))
	self.arrswap = self.arrswap[1:self.arrLen+ 1]
	self.ChangeSize()
	

    def timerEvent(self, event):
	self.updatelabels()
	self.update()
	
  #  def showConfigurationInterface(self):
#	dialog = KPageDialog()
#	dialog.show()
#	widget=QtGui.QWidget()
#	widget.setWindowTitle("Hello Python!")
#	widget.resize(200,150)
#	widget.show()
#	dialog.exec_()
    
   # def createConfigurationInterface(self, parent):
   #     self.configParameters = ConfigParameters(self,  self._settings)
   #     page = parent.addPage(self.configParameters, "Configure Me")
   #     page.setIcon(KIcon("preferences-other"))
     #   self.connect(parent, SIGNAL("okClicked()"), self.configAccepted)
      #  self.connect(parent, SIGNAL("cancelClicked()"), self.configDenied)

    # setup and show configuration dialog (called by plasma)
    def showConfigurationInterface(self):
        self.dialog = KPageDialog()
	self.dialog.setPlainCaption(i18n("Настройка виджета \"SysMonitor-PedaKde\""))
	self.dialog.setInitialSize(QSize(500, 300))
	#page = ColorPage()
	#item = KPageWidgetItem( page, i18n( "Colors" ) )
	#item.setHeader( i18n( "Colors of Main Window" ) )
	#item.setIcon( KIcon( "colors" ) )
	#self.item = KPageWidgetItem(self.Dialoglabel1)
	#self.item.setIcon(KIcon("ram"))
	#self.item.setName(i18n("Использование ОЗУ"))
	
	self.groupBox3 = QGroupBox()
	self.check31 = QCheckBox( i18n("полный вид"))
	if self.seebig == 1:
	      self.check31.setCheckState(Qt.Checked)
	else:
	      self.check31.setCheckState(Qt.Unchecked)
	self.vbox3 = QVBoxLayout()
	self.vbox3.addWidget(self.check31)
	self.groupBox3.setLayout(self.vbox3) 
	self.dialog.addPage(self.groupBox3, i18n( "Общие настройки" )) 

	self.groupBox1 = QGroupBox()
	self.check11 = QCheckBox(i18n( "показывать общую загрузку" ))
	if self.seecpu == 1:
	      self.check11.setCheckState(Qt.Checked)
	else:
	      self.check11.setCheckState(Qt.Unchecked)
	self.check12 = QCheckBox(i18n( "показывать загрузку cpu0" ))
	if self.seecpu0 == 1:
	      self.check12.setCheckState(Qt.Checked)
	else:
	      self.check12.setCheckState(Qt.Unchecked)
	self.check13 = QCheckBox(i18n( "показывать загрузку cpu1" ))
	if self.seecpu1 == 1:
	      self.check13.setCheckState(Qt.Checked)
	else:
	      self.check13.setCheckState(Qt.Unchecked)
	self.vbox1 = QVBoxLayout()
	self.vbox1.addWidget(self.check11)
	self.vbox1.addWidget(self.check12)
	self.vbox1.addWidget(self.check13)
	self.groupBox1.setLayout(self.vbox1) 
	self.dialog.addPage(self.groupBox1, i18n( "Загрузка ЦП" ))    
	
	self.groupBox2 = QGroupBox()
	self.check21 = QCheckBox(i18n( "показывать уровень использ. ОЗУ" ))
	if self.seemem == 1:
	      self.check21.setCheckState(Qt.Checked)
	else:
	      self.check21.setCheckState(Qt.Unchecked)
	self.check22 = QCheckBox(i18n( "показывать уровень использ. ФП" ))
	if self.seeswap == 1:
	      self.check22.setCheckState(Qt.Checked)
	else:
	      self.check22.setCheckState(Qt.Unchecked)
	self.vbox2 = QVBoxLayout()
	self.vbox2.addWidget(self.check21)
	self.vbox2.addWidget(self.check22)
	self.groupBox2.setLayout(self.vbox2) 
	self.dialog.addPage(self.groupBox2, i18n( "Использование ОЗУ" ))
	
	self.Dialoglabel2 = QLabel( "" )
	self.dialog.addPage(self.Dialoglabel2, i18n( "Комбинация клавиш" ))
	
	#self.dialog.setFaceType(KPageDialog.List)
	self.dialog.setButtons(KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel))
	self.connect(self.dialog, SIGNAL("okClicked()"), self.configAccepted)
        #self.connect(parent, SIGNAL("cancelClicked()"), self.configDenied)
	self.dialog.exec_()
    
    def configAccepted(self):
	if self.check31.checkState() == Qt.Checked:
	      self.seebig = 1
	if self.check31.checkState() == Qt.Unchecked:
	      self.seebig = 0
	if self.check11.checkState() == Qt.Checked:
	      self.seecpu = 1
	if self.check11.checkState() == Qt.Unchecked:
	      self.seecpu = 0
	if self.check12.checkState() == Qt.Checked:
	      self.seecpu0 = 1
	if self.check12.checkState() == Qt.Unchecked:
	      self.seecpu0 = 0
	if self.check13.checkState() == Qt.Checked:
	      self.seecpu1 = 1
	if self.check13.checkState() == Qt.Unchecked:
	      self.seecpu1 = 0
	if self.check21.checkState() == Qt.Checked:
	      self.seemem = 1
	if self.check21.checkState() == Qt.Unchecked:
	      self.seemem = 0
	if self.check22.checkState() == Qt.Checked:
	      self.seeswap = 1
	if self.check22.checkState() == Qt.Unchecked:
	      self.seeswap = 0
	self.updatelabels()
	self.update()

    def ChangeSize(self):
	summ = self.seecpu + self.seecpu0 + self.seecpu1 + self.seemem + self.seeswap
	sizex = self.appletW
	sizey = self.appletH
	if self.seebig == 1:
	      sizey = summ * self.hbH + (summ+1)*5 + 60
	      sizex = self.appletW
	else:
	      sizey = summ * self.labelH + summ*5 + 20
	      sizex = 150
	self.resize(sizex, sizey)

    def paintInterface(self, painter, option, rect):
        painter.save()
        #define fonts for legend 
	#classic_legendfont = QFont("Sans Serif", 7)
        painter.setPen(QColor("black"))
	painter.setBrush(QBrush(Qt.SolidPattern))
	
	#painter.drawText(self.begX, self.begY, self.labelW, self.labelH , Qt.TextWordWrap, "Mem: " + self.memuse + "   Swap: " + self.swapuse)
	#painter.drawText(self.begX, self.begY + self.labelH, self.labelW, self.labelH,  Qt.TextWordWrap, "CPU Load : " + self.cpuload + "  " + self.cpu0load + "  "+ self.cpu1load)
	s=0
	if self.seebig == 1:
	      if self.seecpu == 1:
		    painter.drawText( self.begX, self.begY + s*self.labelH + 5*(s+2), 50, self.labelH,  Qt.TextWordWrap, "CPU:")
		    painter.drawText( self.begX, self.begY + (s+1)*self.labelH + 5*(s+1), 50, self.labelH,  Qt.TextWordWrap, self.cpuload)
		    self.paintTableOfWindow(painter, self.begX + 50, self.begY + s*self.labelH + (s+1)*5, self.balanW, self.hbH, float(self.cpuload[0:3]) )
		    self.paintTableHistory(painter, self.begX + 50 + self.balanW + 10 , self.begY + s*self.labelH + 5*(s+1) , self.histoW, self.hbH, self.arrcpu )
		    s+=2
	
	      if self.seecpu0 == 1:
		    painter.drawText( self.begX, self.begY + s*self.labelH + 5*(s+2), 50, self.labelH,  Qt.TextWordWrap, "CPU0:")
		    painter.drawText( self.begX, self.begY + (s+1)*self.labelH + 5*(s+1), 50, self.labelH,  Qt.TextWordWrap, self.cpu0load)
		    self.paintTableOfWindow(painter, self.begX + 50, self.begY + s*self.labelH + (s+1)*5, self.balanW, self.hbH, float(self.cpu0load[0:3]) )
		    self.paintTableHistory(painter, self.begX + 50 + self.balanW + 10 , self.begY + s*self.labelH + 5*(s+1) , self.histoW, self.hbH, self.arrcpu0 )
		    s+=2
	
	      if self.seecpu1 == 1:
		    painter.drawText( self.begX, self.begY + s*self.labelH + 5*(s+2), 50, self.labelH,  Qt.TextWordWrap, "CPU1:")
		    painter.drawText( self.begX, self.begY + (s+1)*self.labelH + 5*(s+1), 50, self.labelH,  Qt.TextWordWrap, self.cpu1load)
		    self.paintTableOfWindow(painter, self.begX + 50, self.begY + s*self.labelH + (s+1)*5, self.balanW, self.hbH, float(self.cpu1load[0:3]) )
		    self.paintTableHistory(painter, self.begX + 50 + self.balanW + 10 , self.begY + s*self.labelH + 5*(s+1) , self.histoW, self.hbH, self.arrcpu1 )
		    s+=2

	      if self.seemem == 1:
		    painter.drawText( self.begX, self.begY + s*self.labelH + 5*(s+2), 50, self.labelH,  Qt.TextWordWrap, "Mem:")
		    painter.drawText( self.begX, self.begY + (s+1)*self.labelH + 5*(s+1), 50, self.labelH,  Qt.TextWordWrap, self.memuse)
		    self.paintTableOfWindow(painter, self.begX + 50, self.begY + s*self.labelH + (s+1)*5, self.balanW, self.hbH, float(self.memuse[0:3]) )
		    self.paintTableHistory(painter, self.begX + 50 + self.balanW + 10 , self.begY + s*self.labelH + 5*(s+1) , self.histoW, self.hbH, self.arrmem )
		    s+=2	

	      if self.seeswap == 1:
		    painter.drawText( self.begX, self.begY + s*self.labelH + 5*(s+2), 50, self.labelH,  Qt.TextWordWrap, "Swap:")
		    painter.drawText( self.begX, self.begY + (s+1)*self.labelH + 5*(s+1), 50, self.labelH,  Qt.TextWordWrap, self.swapuse)
		    self.paintTableOfWindow(painter, self.begX + 50, self.begY + s*self.labelH + (s+1)*5, self.balanW, self.hbH, float(self.swapuse[0:3]) )
		    self.paintTableHistory(painter, self.begX + 50 + self.balanW + 10 , self.begY + s*self.labelH + 5*(s+1) , self.histoW, self.hbH, self.arrswap )
		    s+=2
	else:
	      if self.seecpu == 1:
		    painter.drawText(self.begX, self.begY + s*self.labelH, self.labelW, self.labelH , Qt.TextWordWrap, "CPU :    " + self.cpuload)
		    s+=1
	      if self.seecpu0 == 1:
		    painter.drawText(self.begX, self.begY + s*self.labelH, self.labelW, self.labelH , Qt.TextWordWrap, "CPU0:   " + self.cpu0load)
		    s+=1
	      if self.seecpu1 == 1:
		    painter.drawText(self.begX, self.begY + s*self.labelH, self.labelW, self.labelH , Qt.TextWordWrap, "CPU1:   " + self.cpu1load)
		    s+=1
	      if self.seemem == 1:
		    painter.drawText(self.begX, self.begY + s*self.labelH, self.labelW, self.labelH , Qt.TextWordWrap, "Mem :   " + self.memuse)
		    s+=1
	      if self.seeswap == 1:
		    painter.drawText(self.begX, self.begY + s*self.labelH, self.labelW, self.labelH , Qt.TextWordWrap, "Swap:   " + self.swapuse)
		    s+=1
	painter.restore()
    
    def paintTableOfWindow(self, mypainter, currX, currY, pW, pH, value):
	mypainter.drawLine(currX, currY, currX, currY + pH)
	mypainter.drawLine(currX, currY + pH, currX + pW,  currY + pH)
	mypainter.drawRect(currX, currY + pH - int(value*pH/100), pW ,int(value*pH/100) )
    
    def paintTableHistory(self, mypainter, currX, currY, pW, pH, arrvalue):
	mypainter.drawLine(currX, currY, currX, currY + pH)
	mypainter.drawLine(currX, currY + pH, currX + pW,  currY + pH)
	i=0
	while i < pW:
		mypainter.drawLine(currX + i, currY + pH - int(arrvalue[i]*pH/100), currX + i,  currY +pH)
		i+=1

def CreateApplet(parent):
    return BWCBalancePlasmoid(parent)

